﻿using System;
using System.Collections.Generic;
using System.Text;

namespace TimelineNet {
    public class TimelineAjaxHandler : System.Web.IHttpHandler {
        #region IHttpHandler Members

        public bool IsReusable {
            get { return true; }
        }

        public void ProcessRequest(System.Web.HttpContext context) {
            if(context != null) {
                context.Response.Clear();
                context.Response.ClearContent();
                context.Response.ClearHeaders();
                context.Response.AddHeader("Content-Type", "text/xml");
                string content = "";

                string type = context.Request["type"];
                string DataID = context.Request["DataID"];
                TimelineNet.Library.TimelineData data = null;
                if(type == null)
                    type = "";
                else
                    type = type.ToLower();

                if(type == "" || type == "named") {


                    if(DataID != null && DataID.Trim() != "") {
                        if(context.Cache[DataID] != null) {
                            data = (TimelineNet.Library.TimelineData)context.Cache[DataID];
                            context.Cache.Remove(DataID);
                        }
                    }
                    content = data.ToString();
                } else if(type == "rss") {
                    //lets go out and grab the remote rss feed
                    //lets see if its in cache first
                    string cacheKey = string.Format("{0}_DataCache", DataID);
                    if(context.Cache[cacheKey] != null) {
                        data = (TimelineNet.Library.TimelineData)context.Cache[cacheKey];
                    } else {

                        data = (TimelineNet.Library.TimelineData)context.Cache[DataID];
                        string[] Colors = new string[] {  "red", "green", "blue" };
                        System.Random rnd = new Random();
                        Rss.RssFeed feed = Rss.RssFeed.Read(data.DataUrl);
                        data = new TimelineNet.Library.TimelineData();
                        foreach(Rss.RssChannel chan in feed.Channels) {
                            foreach(Rss.RssItem item in chan.Items) {
                                string title = System.Web.HttpUtility.HtmlEncode(item.Title).Replace("&nbsp;", " ");
                                string desc = System.Web.HttpUtility.HtmlEncode(item.Description).Replace("&nbsp;", " ");                                
                                if(desc.Length > 500) {
                                    desc = string.Format("{0}...", desc.Substring(0, 500));
                                }
                                if(item.Link != null) {
                                    //evt.Link = System.Web.HttpUtility.UrlEncode( item.Link.ToString());
                                    desc = string.Format("{2}<br /><br /><a href=\"{1}\" target\"_new\">More...</a>", item.Title, item.Link.ToString(), desc);
                                }
                                if(item.Author != null && item.Author!="") {
                                    desc = string.Format("{1} wrote {0}", desc, item.Author);
                                }
                                TimelineNet.Library.Event evt = new TimelineNet.Library.Event(item.PubDate, item.PubDate, false, title, "", desc, "");
                                data.Add(evt);
                                context.Cache.Add(cacheKey, data, null, DateTime.MaxValue, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.BelowNormal, null);
                            }
                        }
                    }
                    content = data.ToString();
                } else if(type == "localxml") {
                    string cacheKey = string.Format("{0}_DataCache", DataID);
                    if(context.Cache[cacheKey] != null) {
                        content = (string)context.Cache[cacheKey];
                    } else {
                        data = (TimelineNet.Library.TimelineData)context.Cache[DataID];
                        if(System.IO.File.Exists(data.DataUrl)) {
                            content = System.IO.File.ReadAllText(data.DataUrl);
                            context.Cache.Add(cacheKey, content, null, DateTime.MaxValue, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.BelowNormal, null);
                        }
                    }

                } else if(type == "remotexml") {
                    string cacheKey = string.Format("{0}_DataCache", DataID);
                    if(context.Cache[cacheKey] != null) {
                        content = (string)context.Cache[cacheKey];
                    } else {
                        data = (TimelineNet.Library.TimelineData)context.Cache[DataID];
                        content = TimelineNet.HTTP.Web.HTTPAsString(data.DataUrl, "text/xml");
                        //content = TimelineNet.HTTP.Web.HTTPAsString(data.DataUrl, null);

                        context.Cache.Add(cacheKey, content, null, DateTime.MaxValue, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.BelowNormal, null);
                    }

                } else if(type == "remotevcs") {
                    string cacheKey = string.Format("{0}_DataCache", DataID);
                    if(context.Cache[cacheKey] != null) {
                        content = (string)context.Cache[cacheKey];
                    } else {
                        data = (TimelineNet.Library.TimelineData)context.Cache[DataID];
                        content = TimelineNet.HTTP.Web.HTTPAsString(data.DataUrl, null);
                        //content = TimelineNet.HTTP.Web.HTTPAsString(data.DataUrl, null);
                        Calendar.vCal vcal = new Calendar.vCal();
                        vcal.ParseCal(content);

                        if(vcal.EventList.Count > 0) {
                            data = new TimelineNet.Library.TimelineData();
                            foreach(Calendar.vEvent evt in vcal.EventList) {
                                TimelineNet.Library.Event ev = new TimelineNet.Library.Event(evt.StartDateTime, evt.EndDateTime, true, evt.Subject, "", evt.Description, "");
                                data.Add(ev);
                            } 
                        }
                        content = data.ToString();
                        context.Cache.Add(cacheKey, content, null, DateTime.MaxValue, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.BelowNormal, null);
                    }

                }


                context.Response.Write(content);
            }
        }

        #endregion
    }
}